//
//  ViewController.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/10/14.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "PlayViewController.h"
#import "PlayBottomView.h"
#import "PlayProgressView.h"
#import "LZMusicPlayerManager.h"
#import "SampleQueueId.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ZYLrcView.h"

@interface PlayViewController ()<STKAudioPlayerDelegate>{

    NSTimer* timer;
}
@property (nonatomic,strong) PlayBottomView   *playBottomView;
@property (nonatomic,strong) PlayProgressView *progressView;
@property (nonatomic,strong) UIImageView *coverImageView;  //背景
@property (nonatomic,strong) ZYLrcView *lrcView;  //歌词

/**
 *  显示歌词的定时器
 */
@property (nonatomic, strong) CADisplayLink *lrcTimer;


@end

@implementation PlayViewController

- (void)dealloc{

    [LZMusicPlayerManager shareInstance].audioPlayer.delegate=nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    //lyric_normal play_cover_pic_bg
    [self setupTimer];
    [self updateControls];
    
    [self.view addSubview:self.playBottomView];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.coverImageView];
    [self.coverImageView addSubview:self.lrcView];
    
    [LZMusicPlayerManager shareInstance].audioPlayer.delegate=self;
    
    //锁屏显歌词
    [self showInfoInLockedScreen];
   
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)startPlayWithURLString:(NSString *)urlStr{

    NSURL *url = [NSURL URLWithString:urlStr];
    
    STKDataSource* dataSource = [STKAudioPlayer dataSourceFromURL:url];
    
    [[LZMusicPlayerManager shareInstance].audioPlayer setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
}

- (void)changeLrcClick:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    
    if (sender.selected) { //显示歌词
        
        self.lrcView.hidden = NO;
        
    }else{
        self.lrcView.hidden = YES;
    }
}

#pragma mark -懒加载
- (UIImageView *)coverImageView{

    if (!_coverImageView) {
        
        _coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - self.playBottomView.height)];
        _coverImageView.image = [UIImage imageNamed:@"play_cover_pic_bg"];
        
        //退出
        UIImage *imgBtn = [UIImage imageNamed:@"quit"];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(10,25, imgBtn.size.width, imgBtn.size.height);
        [btn setImage:imgBtn forState:UIControlStateNormal];
        [_coverImageView addSubview:btn];
        
        //歌词切换
        imgBtn = [UIImage imageNamed:@"lyric_select"];
        btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(self.view.width - imgBtn.size.width - 10, 25, imgBtn.size.width, imgBtn.size.height);
        [btn setImage:imgBtn forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"lyric_normal"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(changeLrcClick:) forControlEvents:UIControlEventTouchUpInside];
        [_coverImageView addSubview:btn];
        
    }
    return _coverImageView;
}

- (ZYLrcView *)lrcView {

    if (!_lrcView) {
        _lrcView = [[ZYLrcView alloc] initWithFrame:CGRectMake(0, 30, self.coverImageView.width, self.coverImageView.height - 30)];
        _lrcView.hidden = YES;
    }
    return _lrcView;
}


#pragma mark ----歌词定时器

- (void)addLrcTimer
{
    if (self.lrcView.hidden == YES) return;
    
    if ([LZMusicPlayerManager shareInstance].audioPlayer.state != STKAudioPlayerStatePlaying && self.lrcTimer) {
        [self updateLrcTimer];
        return;
    }
    
    [self removeLrcTimer];
    
    [self updateLrcTimer];
    
    self.lrcTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrcTimer)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)removeLrcTimer
{
    [self.lrcTimer invalidate];
    self.lrcTimer = nil;
}

- (void)updateLrcTimer
{
    self.lrcView.currentTime = [[LZMusicPlayerManager shareInstance].playTime intValue];
}



#pragma mark -歌曲控制

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //接受远程控制
    [self becomeFirstResponder];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)viewDidDisappear:(BOOL)animated {
    //取消远程控制
    [self resignFirstResponder];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

#pragma mark - 锁屏显歌词
// 在锁屏界面显示歌曲信息(实时换图片MPMediaItemArtwork可以达到实时换歌词的目的)
- (void)showInfoInLockedScreen
{
    // 核心:字典
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    
    // 标题(音乐名称)
    info[MPMediaItemPropertyTitle] = @"waiting in the wings";
    
    // 艺术家
    info[MPMediaItemPropertyArtist] = @"Shayne Ward";
    
    // 专辑名称
    info[MPMediaItemPropertyAlbumTitle] = @"Shayne Ward";
    
    //音乐剩余时长
    [info setObject:[NSNumber numberWithDouble:[LZMusicPlayerManager shareInstance].audioPlayer.duration] forKey:MPMediaItemPropertyPlaybackDuration];
    
    //音乐当前播放时间 在计时器中修改
    [info setObject:[NSNumber numberWithDouble:[LZMusicPlayerManager shareInstance].audioPlayer.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    // 图片
    //info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:music.icon]];
    // 唯一的API,单例,nowPlayingInfo字典
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
}

/**
 *  响应远程音乐播放控制消息
 *
 *  @param receivedEvent  事件
 */
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
                //点击了暂停
                [[LZMusicPlayerManager shareInstance].audioPlayer pause];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //点击了下一首
                //[self playNextMusic];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //点击了上一首
                //[self playPreMusic];
                //此时需要更改歌曲信息
                break;
            case UIEventSubtypeRemoteControlPlay:{
                //点击了播放
                //[[LZMusicPlayerManager shareInstance].audioPlayer play];
                
                if ([LZMusicPlayerManager shareInstance].audioPlayer.state == STKAudioPlayerStatePaused){
                    [[LZMusicPlayerManager shareInstance].audioPlayer resume];
                }else{
                    [[LZMusicPlayerManager shareInstance].audioPlayer pause];
                }
                
                break;
            }
            default:
                break;
        }
    }
}


#pragma mark -更新数据

-(void) updateControls
{
    if ([LZMusicPlayerManager shareInstance].audioPlayer == nil)
    {
        [self.playBottomView setPlayStatus:NO];
    }
    else if ([LZMusicPlayerManager shareInstance].audioPlayer.state == STKAudioPlayerStatePaused)
    {
        //[playButton setTitle:@"Resume" forState:UIControlStateNormal];
        DLog(@"state == STKAudioPlayerStatePaused");
        [self.playBottomView setPlayStatus:NO];
    }
    else if ([LZMusicPlayerManager shareInstance].audioPlayer.state & STKAudioPlayerStatePlaying)
    {
        DLog(@"state == STKAudioPlayerStatePlaying");
        //[playButton setTitle:@"Pause" forState:UIControlStateNormal];
        [self.playBottomView setPlayStatus:YES];
    }
    else
    {
        DLog(@"state == no");
        //[playButton setTitle:@"" forState:UIControlStateNormal];
        [self.playBottomView setPlayStatus:NO];
    }
    
    [self tick];
}

-(void) setupTimer
{
    timer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(tick) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void) tick
{
    if (![LZMusicPlayerManager shareInstance].audioPlayer)
    {
        [self.progressView reset];
        return;
    }
    
    if ([LZMusicPlayerManager shareInstance].audioPlayer.currentlyPlayingQueueItemId == nil)
    {
        [self.progressView reset];
        return;
    }
    
    if ([LZMusicPlayerManager shareInstance].audioPlayer.duration != 0)
    {

        [self.progressView setProgress:[LZMusicPlayerManager shareInstance].progress];
        self.progressView.startTimeLabel.text=[LZMusicPlayerManager shareInstance].playTime;
        self.progressView.endTimeLabel.text=[LZMusicPlayerManager shareInstance].duration;
        
    }
    else
    {
        
        [self.progressView reset];
    }
    
    //加载
    
    /**
    
    statusLabel.text = audioPlayer.state == STKAudioPlayerStateBuffering ? @"buffering" : @"";
    
    CGFloat newWidth = 320 * (([audioPlayer averagePowerInDecibelsForChannel:1] + 60) / 60);
    
    meter.frame = CGRectMake(0, 460, newWidth, 20);
     
     **/
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -懒加载

- (PlayBottomView *)playBottomView{
    
    if (!_playBottomView) {
        
        _playBottomView=[PlayBottomView playBottomViewOffsetY:self.view.bounds.size.height-66.0f];
        [_playBottomView setType:^(MusicPlayType playType) {
            
            NSLog(@"playType =%ld",(long)playType);
            
        } prev:^{
            
        } play:^(BOOL playing) {

            //刚开始播放
            id  ItemId =[[LZMusicPlayerManager shareInstance].audioPlayer currentlyPlayingQueueItemId];
            if (ItemId==nil&&playing) {
                NSURL* url = [NSURL URLWithString:@"http://sc.111ttt.com/up/mp3/405122/BA0EAF6EFD484192F6643D3B44D8C235.mp3"];
                
                STKDataSource* dataSource = [STKAudioPlayer dataSourceFromURL:url];
                
                [[LZMusicPlayerManager shareInstance].audioPlayer setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
                
                return;
            }
            
            if ([LZMusicPlayerManager shareInstance].audioPlayer.state == STKAudioPlayerStatePaused){
                 [[LZMusicPlayerManager shareInstance].audioPlayer resume];
            }else{
                 [[LZMusicPlayerManager shareInstance].audioPlayer pause];
            }
            
        } next:^{
            
        } menu:^{
            
        }];
    }
    return _playBottomView;
}

- (PlayProgressView *)progressView{
    
    if (!_progressView) {
        
        _progressView=[PlayProgressView playProgressViewOffsetY:self.playBottomView.frame.origin.y-25];
    }
    return _progressView;
}

#pragma mark - STKAudioPlayerDelegate Methods
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
     DLog(@"%s", __func__);
    
    [self updateControls];
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
     DLog(@"%s", __func__);
    
    [self updateControls];
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
     DLog(@"%s", __func__);
    
    SampleQueueId* queueId = (SampleQueueId*)queueItemId;
    
    DLog(@"Started: %@", [queueId.url description]);
    
    [self updateControls];
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"%s", __func__);
    
    [self updateControls];
    
    // This queues on the currently playing track to be buffered and played immediately after (gapless)
    
    
    if (self.playBottomView.musicPlayType==MusicPlayLoopType) //重复播放
    {
        SampleQueueId* queueId = (SampleQueueId*)queueItemId;
        
        DLog(@"Requeuing: %@", [queueId.url description]);
        
        [[LZMusicPlayerManager shareInstance].audioPlayer queueDataSource:[STKAudioPlayer dataSourceFromURL:queueId.url] withQueueItemId:[[SampleQueueId alloc] initWithUrl:queueId.url andCount:queueId.count + 1]];
    }
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    DLog(@"%s", __func__);
    
    [self updateControls];
    
    SampleQueueId* queueId = (SampleQueueId*)queueItemId;
    
    DLog(@"Finished: %@", [queueId.url description]);
}

-(void) audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line
{
    DLog(@"%s", __func__);
}


@end
